<?php

namespace app\crontab\command;

use fast\Form;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\Lang;
use think\Loader;
use function GuzzleHttp\json_encode;

class Cron extends Command
{

    protected $stubList = [];

    protected function configure()
    {
        $this->setName('cron')
            ->addOption('task', 't', Option::VALUE_REQUIRED, 'TaskName', null)
            ->addOption('function', 'f', Option::VALUE_REQUIRED, 'Function Name', null)
            ->addOption('params', 'p', Option::VALUE_OPTIONAL, 'Params String,Like:"a=12&b=ok"', null)
            ->setDescription('Run timed task for app');
    }

    protected function execute(Input $input, Output $output)
    {
        //任务名称
        $task = $input->getOption('task') ?: '';
        //方法名
        $function = $input->getOption('function')?:'index';
        //参数
        $paramsStr = $input->getOption('params');
        parse_str( $paramsStr, $params );

        if( empty( $task ) )
        {
            return $output->writeln("Unknow Task! TaskName is required!");
        }

        $taskName = "\\app\\crontab\\task\\".ucfirst($task);

        // if( !class_exists( $taskName ) )
        // {
        //     return $output->writeln("{$taskName} dons't exist!");
        // }

        try{

            $class = new $taskName( $params );

            $result = $class->$function();

        }catch(\Exception $e)
        {
            return $output->writeln("Exception::{$e->getMessage()}");
        }
        
        $output->writeln( json_encode($result,JSON_UNESCAPED_UNICODE) );
    }
}